package uk.ac.ebi.literature.utils.file;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import org.apache.log4j.Logger;

import uk.ac.ebi.literature.utils.string.StringUtils;

public class CsvUtils {
    public final static Logger logger = Logger.getLogger(CsvUtils.class.getName());
    
    public static final String CSVFILE = "GTL_list_for_Jo.csv";

    public static void main(String[] args) {

        CsvUtils obj = new CsvUtils();
        obj.run();

    }

    public void run() {

        String csvFile = "src/main/resources/GTL_list_for_jo.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";

        try {

            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] info = line.split(cvsSplitBy);

                StringBuilder details = new StringBuilder();
                details.append("Name = ");
                details.append(info[1]);
                details.append(" ");
                details.append(info[0]);
                details.append(", Emails = ");
                details.append(info[2]);

                System.out.println(details.toString());

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * Parse CSV file into a list of OrcidId
     * 
     * CSV format: family name, given name, email
     * 
     * @param fileName
     * @param keyCol, starting with 0
     * @return
     * @throws Exception: Invalid input CSV file
     */
    public static HashMap<String, ArrayList<String>> parseCsvToMap(String fileName, int keyCol) throws Exception {
        HashMap<String, ArrayList<String>> keyValuesMap = new HashMap<String, ArrayList<String>>();
        if (fileName == null || keyCol < 0) {
            return keyValuesMap;
        }
        
        String cvsSplitBy = ",";
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        
        String line;
        while ((line = br.readLine()) != null) {

            if (!StringUtils.hasContent(line)) {
                continue;
            }
            
            // use comma as separator
            String[] detail = line.split(cvsSplitBy);
            if (detail == null) {
                if (br != null) {
                    br.close();
                }
                throw new Exception("Invalid line: " + line);
            }
            if (keyCol > detail.length - 1) {
                if (br != null) {
                    br.close();
                }
                throw new Exception("Mal formatted line: " + line);
            }
            
            String key = detail[keyCol].trim().toLowerCase();            
            ArrayList<String> valueList = new ArrayList<String>();
            for (String value: detail) {
                valueList.add(value.trim());
            }
            
            keyValuesMap.put(key, valueList);
        }
        
        if (br != null) {
            br.close();
        }
        return keyValuesMap;
    }

    /**
     * Parse CSV file into a list of OrcidId
     * 
     * CSV format: family name, given name, email
     * 
     * @param fileName
     * @param recordList
     * @return
     */
    public static boolean writeToCsv(String fileName, Collection<ArrayList<String>> recordList) {
        if (fileName == null || recordList == null) {
            return false;
        }
        
        StringBuilder csvRecord = new StringBuilder();
        
        for (ArrayList<String> record: recordList) {
            for (String value: record) {
                csvRecord.append(value);
                csvRecord.append(",");
            }
            csvRecord.append("\n");
        }
        
        FileWriter writer;
        try {
            writer = new FileWriter(fileName);
            writer.append(csvRecord);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            String errMsg = String.format("Failed to export CSV: %s (%s)", fileName, e.getMessage());
            logger.error(errMsg);
            return false;
        }
        
        return true;
    }
}